
package com.lagou.seckill.common.exceptions;

import com.lagou.seckill.common.enums.ErrorCodeEnum;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.ResponseStatus;

@Data
@Slf4j
public class CustomException extends RuntimeException {
    /**
     * 错误码
     */
    private final String code;

    public CustomException(String code, String message) {
        super(message);
        if (code == null || !StringUtils.hasText(code)) {
            this.code = ErrorCodeEnum.SYSTEM_ERROR_B0001.getCode();
        } else {
            this.code = code;
        }
    }

    @ResponseStatus(value = HttpStatus.NOT_FOUND)
    public static class NotFoundException extends CustomException {
        public NotFoundException(ErrorCodeEnum message) {
            super(message.getCode(), message.getDescription());
        }
    }

    @ResponseStatus(value = HttpStatus.FORBIDDEN)
    public static class AuthorizationException extends CustomException {
        public AuthorizationException(ErrorCodeEnum message) {
            super(message.getCode(), message.getDescription());
        }
    }

    @ResponseStatus(value = HttpStatus.UNAUTHORIZED)
    public static class AuthenticationException extends CustomException {
        public AuthenticationException(ErrorCodeEnum message) {
            super(message.getCode(), message.getDescription());
        }
    }

    public static class ServiceException extends CustomException {
        public ServiceException(String message) {
            super(ErrorCodeEnum.SYSTEM_ERROR_B0001.getCode(), message);
        }

        public ServiceException(ErrorCodeEnum errorCodeEnum) {
            super(errorCodeEnum.getCode(), errorCodeEnum.getDescription());
        }

        public ServiceException(ErrorCodeEnum errorCodeEnum, Exception e) {
            super(errorCodeEnum.getCode(), errorCodeEnum.getDescription());
            log.error(errorCodeEnum.getDescription(), e);
        }

        public ServiceException(String code, String message) {
            super(code, message);
        }

        public ServiceException(String code, String message, Exception e) {
            super(code, message);
            log.error(message, e);
        }

    }

    public static class ServiceExceptionSecond extends CustomException {
        public ServiceExceptionSecond(String message) {
            super(ErrorCodeEnum.SYSTEM_ERROR_B0001.getCode(), message);
        }
    }

}
